/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package cn.chenmg.DataModel;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author chenmg
 */
public class DataProvider {
    //指定驱动名
   protected static String DBdriver = "com.mysql.jdbc.Driver";
   //指定访问的URL
   protected static String url = "jdbc:mysql://localhost:3306/test";
   //MySQL用户名
   protected static String SQLUser = "root";
   //MySQL密码
   protected static String SQLPassword = "root";
   //初始化Conncection
   protected static Connection connection = null;
   
   //建立连接
   public static Connection getConnection(){
       try {
           Class.forName(SQLUser);
           connection = DriverManager.getConnection(url,SQLUser,SQLPassword);
           return connection;
       }catch(ClassNotFoundException | SQLException e){
           e.printStackTrace();
           return null;
       }
   }
   //获得结果集
   public static ResultSet getResultSet(String sql){
       //Statement类主要用于执行静态SQL语句并返回生成结果的对象
       Statement statement;
       ResultSet resultSet = null;
       Connection conn = getConnection();
       if(conn !=null ){
       System.out.println("连接成功！");
       try{
           //通过Connection对象的createStatement()方法创建Statement对象
           statement = conn.createStatement();
           //调用Statement对象执行SQL语句
           resultSet = statement.executeQuery(sql);
       }catch(Exception e){
       }
       return resultSet;

       }else
           return null;
   }
   //判断结果集是否为空
   public static boolean isResultSetNull(String sql){
       int count = 0;
       ResultSet resultSet = getResultSet(sql);
       try{
           while(resultSet.next()){
               count++;
           }
       }catch(SQLException ex){
           Logger.getLogger(DataProvider.class.getName()).log(Level.SEVERE,null,ex);
       }
       if(count == 0){
           return true;
       }else{
          return false;
       }
   }
   //判断是否执行的函数
   public static boolean execute(String sql){
       boolean success;
       Statement statement;
       Connection conn = getConnection();
       if(conn != null){
           try{
               statement = conn.createStatement();
               success = statement.execute(sql);
           }catch(SQLException e){
               success = false;
           }
       }else{
           success = false;
       }
       return success;
   }
   //释放连接
   public static void releaseConnection(){
       try{
           if(connection != null){
               connection.close();
           }
       }catch(SQLException e){
       }
   }
}
